package com.juc.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author Zan
 * @Create 2024/5/7 12:56
 * @ClassName : SaleTicketDemo
 * @Description : TODO 请用一句话描述该类的功能
 */
public class SaleTicketDemo {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        new Thread(() -> {
            for (int i = 0; i < 55; i++) {
                ticket.sale();
            }
        }, "a").start();

        new Thread(() -> {
            for (int i = 0; i < 55; i++) {
                ticket.sale();
            }
        }, "b").start();

        new Thread(() -> {
            for (int i = 0; i < 55; i++) {
                ticket.sale();
            }
        }, "c").start();
    }
}

class Ticket { // 资源类，模拟3个售票员卖完50张票

    private int number = 50;

    ReentrantLock lock = new ReentrantLock(true);

    public void sale() {
        lock.lock(); // 加锁
        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出第" + (number--) + "张票，还剩下" + number + "张票");
            }
        } finally {
            lock.unlock(); // 解锁
        }
    }
}
